const express = require("express");
const {getUnix} = require("../../model/tools");
const NavModel = require("../../model/NavModel");

var router = express.Router();
router.get("/", async (req, res) => {
    let result = await NavModel.find()

    res.render("admin/nav/index.html", {
        list: result
    })
})


router.get("/add", async (req, res) => {

    res.render("admin/nav/add.html")

})


router.get("/edit", async (req, res) => {
    let id = req.query.id

    let result = await NavModel.find({"_id": id})

    if (result.length) {
        res.render("admin/nav/edit.html", {
            list: result[0]
        })
    } else {
        res.redirect(`/${req.app.locals.adminPath}/nav`)
    }
})


router.post("/doAdd", async (req, res) => {
    // let { title, link, postion, is_opennew, sort, status } = req.body

    let result = new NavModel(Object.assign( req.body, {add_time: getUnix()} ))

    await result.save()

    res.render("admin/public/success.html", {
        "redirectUrl": `/${req.app.locals.adminPath}/nav`,
        "message": "增加导航成功"
    })
})

router.post("/doEdit", async (req, res) => {
    await NavModel.updateOne({"_id": req.body.id}, req.body)

    res.render("admin/public/success.html", {
        "redirectUrl": `/${req.app.locals.adminPath}/nav`,
        "message": "修改导航成功"
    })
})

router.get("/delete", async (req, res) => {
    let id = req.query.id

    let result = await NavModel.deleteOne({"_id": id})

    if (result) {
        res.render("admin/public/success.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/nav`,
            "message": "删除导航成功"
        })
    }
})

module.exports = router